# This file is part of ModularBot.
# Copyright (C) 2005 Pierre Ducroquet (pierre.linux59@wanadoo.fr)

# ModularBot is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# ModularBot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with ModularBot; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import imp, time, sys

class RightsManager:
	def __init__ (self, config):
		self.logins = {}
		self.config = config
		(self.filename, args) = config.split("(", 1)
		self.args = args[:-1].split(";")
		self.plugin = None
		self.parse()
	
	def close (self):
		if self.plugin != None and hasattr(self.plugin, "close"):
			self.plugin.close()
	
	def parse (self):
		if self.plugin != None and hasattr(self.plugin, "close"):
			self.plugin.close()
		new_plugin_mod = imp.load_source("", self.filename)
		self.plugin = new_plugin_mod.RightsPlugin(*self.args)
		self.plugin.parse()
	
	def has_right (self, user, right):
		try:
			return self.plugin.has_right(user, right)
		except:
			infos = sys.exc_info()
			sys.excepthook(infos[0], infos[1], infos[2])
			print "Exception catched"
			return False
	
	def is_core_admin (self, user):
		try:
			return self.plugin.is_core_admin(user)
		except:
			infos = sys.exc_info()
			sys.excepthook(infos[0], infos[1], infos[2])
			print "Exception catched"
			return False
	
	def is_admin (self, user):
		try:
			return self.plugin.is_admin(user)
		except:
			infos = sys.exc_info()
			sys.excepthook(infos[0], infos[1], infos[2])
			print "Exception catched"
			return False
	
	def login (self, user, passwd):
		try:
			if self.plugin.check_passwd(user, passwd):
				self.logins[user] = time.time() + 480
				return True
			else:
				return False
		except:
			infos = sys.exc_info()
			sys.excepthook(infos[0], infos[1], infos[2])
			print "Exception catched"
			return False
	
	def logged_in (self, user):
		if self.logins.has_key(user):
			if self.logins[user] > time.time():
				return True
			else:
				del self.logins[user]
		return False
	
	def logout (self, user):
		if self.logged_in (user):
			del self.logins[user]
			return True
		else:
			return False
